package com.leilbase.adminservice.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class AjaxExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public String defaultErrorHandler(HttpServletRequest request, Exception e) {
        if (isAjax(request)) {
            log.warn("是ajax请求");
        } else {
            log.warn("不是ajax请求");
        }
        e.printStackTrace();
        return "发生了异常：" + e.hashCode() + "===" + e.getMessage();
    }

    /**
     * 判断请求是否为ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }


}
